package com.atguigu.gmall.common.demo;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.primitives.Bytes;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Producer01 {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @SneakyThrows
    public static void send(List<Person> list) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("/");
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("XXXX");
        factory.setPassword("XXXX");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare("realTimeData", BuiltinExchangeType.TOPIC,true);
        channel.queueDeclare("queue",true,false,false,null);
        list.forEach(person -> {
            List<Datas> datas = person.getDatas();
            datas.forEach(data -> {
                desEncript(data, "密钥");
            });
        });
        String message = JSON.toJSONString(list);
        channel.basicPublish("realTimeData","queue",null,message.getBytes());

        channel.close();
        connection.close();
    }
    //AES加密方法
    @SneakyThrows
    public static Datas desEncript(Datas datas, String originKey){
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec key = new SecretKeySpec(originKey.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE,key);
        cipher.doFinal(datas.getCollectDate().getBytes());
        return datas;
    }
}
